package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.domain.Setmeal;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 套餐数据的实现类
 */
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;


    /**
     * 套餐的新增
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        if (ObjectUtils.isEmpty(setmeal) || StringUtils.isEmpty(setmeal.getCode()) || StringUtils.isEmpty(setmeal.getName())) {
            throw new RuntimeException("关键数据不能为空");
        }
        setmealDao.addSetmeal(setmeal);
        if (checkgroupIds != null || checkgroupIds.length > 0) {
            this.addSetmealAndCheckGroup(setmeal, checkgroupIds);
        }
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_RESOURCES_DB, setmeal.getImg());
        jedis.close();


        //生成静态页面
        generateMobileStaticHtml();


    }


    /**
     * 生成静态页面
     */
    private void generateMobileStaticHtml() {
        List<Setmeal> setmealList = setmealDao.findAll();
        setmealHtml(setmealList);
        setmeal_detailHtml(setmealList);
    }

    /**
     * 创建套餐列表静态页面
     *
     * @param setmealList
     */
    private void setmealHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmealList);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    /**
     * 创建套餐详情静态页面
     *
     * @param setmealList
     */
    private void setmeal_detailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Setmeal assocateSetmeal = setmealDao.findAssociateById(setmeal.getId());
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", assocateSetmeal);
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }


    /**
     * 通用创建静态页面模板
     *
     * @param templateName
     * @param htmlPageName
     * @param map
     */
    private void generateHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate(templateName);
            FileWriter fileWriter = new FileWriter(outPutPath + htmlPageName);
            template.process(map, fileWriter);
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加关联检查组
     *
     * @param setmeal
     * @param checkgroupIds
     */
    public void addSetmealAndCheckGroup(Setmeal setmeal, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealAndCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
    }

    /**
     * 套餐分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByCondition(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealDao.findByCondition(queryString);
        List<Setmeal> result = setmeals.getResult();
        long total = setmeals.getTotal();
        return new PageResult(total, result);
    }

    /**
     * 删除套餐
     *
     * @param id
     */
    @Transactional
    @Override
    public void deleteSetmeal(Integer id) {
        long countCheckGroup = setmealDao.findAssocateCheckGroupCount(id);
        if (countCheckGroup > 0) {
            throw new RuntimeException("清除关联后进行删除操作");
        }
        Setmeal setmeal = setmealDao.findById(id);
        QiniuUtils.deleteFileFromQiniu(setmeal.getImg());
        Jedis jedis = jedisPool.getResource();
        Set<String> sinterImgs = jedis.sinter(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_RESOURCES_DB);
        if (sinterImgs != null && sinterImgs.size() > 0) {
            for (String sinterImg : sinterImgs) {
                QiniuUtils.deleteFileFromQiniu(sinterImg);
                jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES, sinterImg);
                jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES_DB, sinterImg);
            }
        }
        jedis.close();
        setmealDao.deleteSetmeal(id);

        //生成静态页面
        generateMobileStaticHtml();
    }

    /**
     * 根据套餐ID查询关联的检查组ID
     *
     * @param id
     * @return
     */
    @Override
    public Integer[] findAssocateCheckGroupIds(Integer id) {
        return setmealDao.findAssocateCheckGroupIds(id);
    }

    /**
     * 根据ID查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    /**
     * 修改套餐
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        if (ObjectUtils.isEmpty(setmeal) || ObjectUtils.isEmpty(setmeal.getId())) {
            throw new RuntimeException("关键数据不能为空");
        }
        if (StringUtils.isEmpty(setmeal.getCode()) || StringUtils.isEmpty(setmeal.getName())) {
            throw new RuntimeException("关键数据不能为空");
        }
        setmealDao.updateSetmeal(setmeal);
        setmealDao.deleteAssocate(setmeal.getId());
        this.addSetmealAndCheckGroup(setmeal, checkgroupIds);

        //生成静态页面
        generateMobileStaticHtml();
    }

    /**
     * 查询所有套餐
     *
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    /**
     * 根据id查询套餐数据和相关联的数据
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findAssociateById(Integer id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new RuntimeException("关键数据不能为空");
        }
        return setmealDao.findAssociateById(id);
    }


    /**
     * 查询各个套餐预约数量
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealOrderCount() {
        return setmealDao.findSetmealOrderCount();
    }
}
